package ginx

import (
	"context"
	"gitee.com/dn-jinmin/authx"
	"github.com/gin-gonic/gin"
)

type ErrResp func(ctx *gin.Context, err error)

var (
	Authx     authx.Authx
	ErrorResp ErrResp
)

func LoadAuth(srv *gin.Engine, opts ...Option) (err error) {
	opt := newOption(opts...)

	if opt.Authx != nil {
		Authx = opt.Authx
	} else {
		Authx, err = authx.NewAuthx(opt.dsn)
		if err != nil {
			return err
		}
	}

	if opt.routeWhite != nil {
		Authx.SetWhite(opt.routeWhite)
	} else {
		opt.routeWhite = make(map[string]string)
	}

	if opt.loadSrvApi {
		// 加载服务api
		for _, r := range srv.Routes() {
			if opt.routeWhite[r.Path] == r.Method {
				continue
			}
			Authx.ApiInsert(context.Background(), r.Path, r.Method)
		}
	}

	if opt.loadAuth {
		//srv.Use(AuthJwt(opt.secret))
	}

	if opt.errResp != nil {
		ErrorResp = opt.errResp
	}
	return nil
}
